<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
        label-width="80px"
        class="search-form"
    >
      <el-form-item label="姓名" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
            v-model="queryParams.phone"
            placeholder="请输入手机号"
            clearable
            @keyup.enter="handleQuery"
            maxlength="11"
        />
      </el-form-item>
      <el-form-item label="工作地点" prop="workPlace">
        <el-input
            v-model="queryParams.workPlace"
            placeholder="请输入工作地点"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="注册时间" prop="joinTime">
        <el-date-picker
            v-model="queryParams.joinTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择日期"
            style="width: 100%"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:rider:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:rider:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:rider:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:rider:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table
        v-loading="loading"
        :data="riderList"
        @selection-change="handleSelectionChange"
        highlight-current-row
        stripe
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="骑手ID" align="center" prop="riderId" width="100" />
      <el-table-column label="骑手头像" align="center" prop="riderImage" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.riderImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" prop="name" width="120" />
      <el-table-column label="手机号" align="center" prop="phone" width="150" />
      <el-table-column label="工作类型" align="center" width="120">
        <template #default="{ row }">
          <el-tag :type="row.jobType === 1 ? 'primary' : 'warning'">
            {{ getJobTypeText(row.jobType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="工作地点" align="center" prop="workPlace" show-overflow-tooltip />
      <el-table-column label="实名认证" align="center" width="120">
        <template #default="{ row }">
          <el-tag :type="row.realNameVerified === 1 ? 'success' : 'info'">
            {{ getRealNameVerifiedText(row.realNameVerified) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="骑手状态" align="center" width="120">
        <template #default="{ row }">
          <el-tag :type="getAuditStatusTagType(row.auditStatus)">
            {{ getAuditStatusText(row.auditStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="账号状态" align="center" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" align="center" width="180">
        <template #default="{row}">
          <span>{{ parseTime(row.joinTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="操作"
          align="center"
          width="180"
          class-name="small-padding fixed-width"
          fixed="right"
      >
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:rider:edit']"
          >修改</el-button>
          <el-button
              link
              type="danger"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:rider:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加/修改对话框 -->
    <el-dialog
        :title="title"
        v-model="open"
        width="600px"
        append-to-body
        :close-on-click-modal="false"
    >
      <el-form ref="riderRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工作类型" prop="jobType">
              <el-select v-model="form.jobType" placeholder="请选择工作类型" style="width:100%">
                <el-option
                    v-for="item in jobTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账号状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择账号状态" style="width:100%">
                <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工作地点" prop="workPlace">
              <el-input v-model="form.workPlace" placeholder="请输入工作地点" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="骑手状态" prop="auditStatus">
              <el-select v-model="form.auditStatus" placeholder="请选择骑手状态" style="width:100%">
                <el-option
                    v-for="item in auditStatusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="实名认证" prop="realNameVerified">
              <el-radio-group v-model="form.realNameVerified">
                <el-radio :label="1">已认证</el-radio>
                <el-radio :label="0">未认证</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册时间" prop="joinTime">
              <el-date-picker
                  v-model="form.joinTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择注册时间"
                  style="width:100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="骑手头像" prop="riderImage">
          <image-upload v-model="form.riderImage"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Rider">
import { listRider, getRider, delRider, addRider, updateRider } from "@/api/system/rider"

const { proxy } = getCurrentInstance()

const riderList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 工作类型选项
const jobTypeOptions = [
  { value: 0, label: '兼职众包' },
  { value: 1, label: '全职专送' }
]

// 账号状态选项
const statusOptions = [
  { value: 1, label: '正常' },
  { value: 2, label: '停用' }
]
const auditStatusOptions = [
  { value: 0, label: '未开通' },
  { value: 1, label: '接单中' },
  { value: 2, label: '休息中' }
]
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    phone: null,
    jobType: null,
    workPlace: null,
    realNameVerified: null,
    auditStatus: null,
    status: null,
    joinTime: null,
    riderImage: null
  },
  rules: {
    name: [
      { required: true, message: "姓名不能为空", trigger: "blur" },
      { min: 2, max: 10, message: "姓名长度在2到10个字符", trigger: "blur" }
    ],
    phone: [
      { required: true, message: "手机号不能为空", trigger: "blur" }
    ],
    jobType: [
      { required: true, message: "请选择工作类型", trigger: "change" }
    ],
    workPlace: [
      { required: true, message: "工作地点不能为空", trigger: "blur" }
    ],
    realNameVerified: [
      { required: true, message: "请选择实名认证状态", trigger: "change" }
    ],
    status: [
      { required: true, message: "请选择账号状态", trigger: "change" }
    ],
    joinTime: [
      { required: true, message: "请选择注册时间", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询骑手列表 */
function getList() {
  loading.value = true
  // 修改后的查询参数，直接使用 joinTime 作为单个日期
  listRider(queryParams.value).then(response => {
    riderList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 工作类型转换
function getJobTypeText(type) {
  const map = { 0: '兼职众包', 1: '全职专送' }
  return map[type] || '未知'
}

// 实名认证状态转换
function getRealNameVerifiedText(verified) {
  const map = { 0: '未认证', 1: '已认证' }
  return map[verified] || '未知'
}

// 骑手状态转换
function getAuditStatusText(status) {
  const map = { 0: '未开通', 1: '接单中', 2: '休息中' }
  return map[status] || '未知'
}

// 骑手状态标签类型
function getAuditStatusTagType(status) {
  const map = { 0: 'info', 1: 'success', 2: 'warning' }
  return map[status] || 'danger'
}

// 账号状态转换
function getStatusText(status) {
  const map = { 1: '正常', 2: '停用' }
  return map[status] || '未知'
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    riderId: null,
    name: null,
    phone: null,
    jobType: null,
    workPlace: null,
    realNameVerified: null,
    auditStatus: null,
    status: null,
    joinTime: null,
    riderImage: null
  }
  proxy.resetForm("riderRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  queryParams.value.joinTime = null
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.riderId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加骑手信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const riderId = row.riderId || ids.value[0]
  getRider(riderId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改骑手信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["riderRef"].validate(valid => {
    if (valid) {
      const isAdd = form.value.riderId == null
      const api = isAdd ? addRider(form.value) : updateRider(form.value)

      api.then(response => {
        proxy.$modal.msgSuccess(isAdd ? "新增成功" : "修改成功")
        open.value = false
        getList()
      })
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const riderIds = row.riderId || ids.value
  proxy.$modal.confirm(`是否确认删除骑手ID为"${riderIds}"的数据项？`).then(() => {
    return delRider(riderIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/rider/export', {
    ...queryParams.value
  }, `骑手信息_${new Date().getTime()}.xlsx`)
}

//文件下载


// 初始化加载数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}
.mb8 {
  margin-bottom: 20px;
}
</style>